<script setup>
import { onMounted, reactive, ref, computed } from 'vue'
import { queryActivityList, getActivityDetail, applyActivity, cancelApplication, getApplicationStatus } from '@/api/student'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Picture } from '@element-plus/icons-vue'

const query = reactive({
    name: '',
    status: undefined,
    page: 1,
    limit: 5
})

const tableData = ref([])
const total = ref(0)
const detailDialogVisible = ref(false)
const activityDetail = ref({})
const applicationStatus = ref(null) // 报名状态
const loading = ref(false)

const getStatusName = (status) => {
    switch (status) {
        case 1: return '未开始'
        case 2: return '报名中'
        case 3: return '进行中'
        case 4: return '已结束'
        case 5: return '已取消'
        default: return '-'
    }
}

const getStatusTagType = (status) => {
    switch (status) {
        case 1: return 'info'
        case 2: return 'success'
        case 3: return 'warning'
        case 4: return 'danger'
        case 5: return 'danger'
        default: return 'info'
    }
}

const fmtDate = (d) => {
    if (!d) return '-'
    try {
        // LocalDate 字符串如 2025-10-20，直接展示
        return String(d)
    } catch (e) {
        return String(d)
    }
}

const loadData = (page) => {
    if (typeof page === 'number') {
        query.page = page
    }
    queryActivityList(query).then(res => {
        tableData.value = res.data || []
        total.value = res.count || 0
    })
}


const showActivityDetail = async (activityId) => {
    try {
        if (!activityId) {
            ElMessage.error('活动ID不能为空')
            return
        }

        const res = await getActivityDetail(activityId)

        if (res && res.data) {
            activityDetail.value = res.data
            // 获取报名状态
            await fetchApplicationStatus(activityId)
            detailDialogVisible.value = true
        } else {
            ElMessage.error('活动详情数据为空')
        }
    } catch (error) {
        console.error('获取活动详情失败:', error)
        ElMessage.error(`获取活动详情失败: ${error.response?.data?.message || error.message || '未知错误'}`)
    }
}

// 获取报名状态
const fetchApplicationStatus = async (activityId) => {
    try {
        const res = await getApplicationStatus(activityId)
        applicationStatus.value = res.data
    } catch (error) {
        console.error('获取报名状态失败:', error)
        applicationStatus.value = null
    }
}

// 计算按钮显示
const buttonConfig = computed(() => {
    const activity = activityDetail.value
    const status = applicationStatus.value

    // 活动已开始、进行中或已结束
    if (activity.status >= 3) {
        return {
            show: true,
            text: activity.status === 3 ? '活动进行中' : '活动已结束',
            type: 'info',
            disabled: true
        }
    }

    // 活动已取消
    if (activity.status === 5) {
        return {
            show: true,
            text: '活动已取消',
            type: 'info',
            disabled: true
        }
    }

    // 未报名
    if (!status || !status.hasApplied || (status.isDeleted === 1)) {
        return {
            show: true,
            text: '立即报名',
            type: 'primary',
            disabled: false,
            action: 'apply'
        }
    }

    // 已报名 - 待审核
    if (status.status === 0) {
        return {
            show: true,
            text: '取消报名',
            type: 'danger',
            disabled: false,
            action: 'cancel'
        }
    }

    // 已报名 - 审核通过
    if (status.status === 1) {
        return {
            show: true,
            text: '已通过审核',
            type: 'success',
            disabled: true
        }
    }

    // 已报名 - 审核不通过
    if (status.status === 2) {
        return {
            show: true,
            text: '重新报名',
            type: 'warning',
            disabled: false,
            action: 'apply'
        }
    }

    return { show: false }
})

// 处理报名/取消按钮点击
const handleAction = async () => {
    const action = buttonConfig.value.action
    const activityId = activityDetail.value.id

    if (action === 'apply') {
        await handleApply(activityId)
    } else if (action === 'cancel') {
        await handleCancel(activityId)
    }
}

// 报名
const handleApply = async (activityId) => {
    try {
        loading.value = true
        const res = await applyActivity(activityId)
        ElMessage.success(res.msg || '报名成功')
        // 刷新报名状态
        await fetchApplicationStatus(activityId)
        // 刷新列表
        loadData(query.page)
    } catch (error) {
        ElMessage.error(error.msg || error.message || '报名失败')
    } finally {
        loading.value = false
    }
}

// 取消报名
const handleCancel = async (activityId) => {
    try {
        await ElMessageBox.confirm('确定要取消报名吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })

        loading.value = true
        const res = await cancelApplication(activityId)
        ElMessage.success(res.msg || '取消报名成功')
        // 刷新列表
        loadData(query.page)
        // 刷新报名状态
        await fetchApplicationStatus(activityId)
    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error(error.msg || error.message || '取消失败')
        }
    } finally {
        loading.value = false
    }
}

onMounted(() => {
    loadData(1)
})
</script>

<template>
    <el-card class="page-container">
        <template #header>
            <div class="header">
                <span>学生活动</span>
            </div>
        </template>

        <div style="margin-bottom: 12px; display: flex; gap: 12px; align-items: center;">
            <el-input v-model="query.name" placeholder="按活动名称搜索" clearable style="width: 220px;" />
            <el-select v-model="query.status" placeholder="活动状态" clearable style="width: 160px;">
                <el-option :value="1" label="未开始" />
                <el-option :value="2" label="报名中" />
                <el-option :value="3" label="进行中" />
                <el-option :value="4" label="已结束" />
                <el-option :value="5" label="已取消" />
            </el-select>
            <el-button type="primary" @click="loadData(1)">查询</el-button>
        </div>

        <el-table :data="tableData" border>
            <el-table-column prop="activityImage" label="封面" width="100">
                <template #default="{ row }">
                    <el-image v-if="row.activityImage" :src="row.activityImage" style="width: 64px; height: 40px;"
                        fit="cover" />
                </template>
            </el-table-column>
            <el-table-column prop="activityName" label="活动名称" min-width="180" />
            <el-table-column label="开始时间" width="120">
                <template #default="{ row }">{{ fmtDate(row.activityStartTime) }}</template>
            </el-table-column>
            <el-table-column label="结束时间" width="120">
                <template #default="{ row }">{{ fmtDate(row.activityEndTime) }}</template>
            </el-table-column>
            <el-table-column label="报名截止" width="120">
                <template #default="{ row }">{{ fmtDate(row.activitySignUpDeadline) }}</template>
            </el-table-column>
            <el-table-column label="报名/上限" width="100">
                <template #default="{ row }">{{ row.activitySignUpNum }}/{{ row.activitySignUpLimit }}</template>
            </el-table-column>
            <el-table-column label="状态" width="100">
                <template #default="{ row }">
                    <el-tag :type="getStatusTagType(row.activitySignUpStatus)">
                        {{ getStatusName(row.activitySignUpStatus) }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="120" fixed="right">
                <template #default="{ row }">
                    <el-button type="primary" size="small" @click="showActivityDetail(row.activityId || row.id)">
                        查看详情
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <div style="margin-top: 12px; text-align: right;">
            <el-pagination background layout="prev, pager, next, jumper, total" :total="total" :page-size="query.limit"
                :current-page="query.page" @current-change="loadData" />
        </div>
    </el-card>

    <!-- 活动详情弹框 -->
    <el-dialog v-model="detailDialogVisible" title="活动详情" width="70%" :before-close="() => detailDialogVisible = false">
        <div v-if="activityDetail" class="activity-detail">
            <div class="detail-header">
                <div class="activity-image-container">
                    <el-image v-if="activityDetail.image || activityDetail.activityImage"
                        :src="activityDetail.image || activityDetail.activityImage" class="activity-image" fit="cover"
                        :preview-src-list="[activityDetail.image || activityDetail.activityImage]" preview-teleported>
                        <template #error>
                            <div class="image-error">
                                <el-icon>
                                    <Picture />
                                </el-icon>
                                <span>图片加载失败</span>
                            </div>
                        </template>
                    </el-image>
                    <div v-else class="no-image">
                        <el-icon>
                            <Picture />
                        </el-icon>
                        <span>暂无图片</span>
                    </div>
                </div>
                <div class="detail-info">
                    <h2 class="activity-title">{{ activityDetail.name || activityDetail.activityName || '未知活动' }}</h2>
                    <p class="detail-text">{{ activityDetail.activityDetail || activityDetail.detail || '暂无详细描述' }}</p>
                </div>
            </div>

            <el-divider />

            <div class="detail-content">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <div class="detail-item">
                            <label>封面图片：</label>
                            <span>{{ activityDetail.image ? '已上传' : '暂无' }}</span>
                        </div>
                    </el-col>
                    <el-col :span="12">
                        <div class="detail-item">
                            <label>活动名称：</label>
                            <span>{{ activityDetail.name }}</span>
                        </div>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <div class="detail-item">
                            <label>活动开始时间：</label>
                            <span>{{ fmtDate(activityDetail.activityStartTime) }}</span>
                        </div>
                    </el-col>
                    <el-col :span="12">
                        <div class="detail-item">
                            <label>活动结束时间：</label>
                            <span>{{ fmtDate(activityDetail.activityEndTime) }}</span>
                        </div>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <div class="detail-item">
                            <label>报名开始时间：</label>
                            <span>{{ fmtDate(activityDetail.signupStartTime) }}</span>
                        </div>
                    </el-col>
                    <el-col :span="12">
                        <div class="detail-item">
                            <label>报名结束时间：</label>
                            <span>{{ fmtDate(activityDetail.signupEndTime) }}</span>
                        </div>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <div class="detail-item">
                            <label>活动状态：</label>
                            <el-tag :type="getStatusTagType(activityDetail.status)">
                                {{ getStatusName(activityDetail.status) }}
                            </el-tag>
                        </div>
                    </el-col>
                    <el-col :span="12">
                        <div class="detail-item">
                            <label>活动地点：</label>
                            <span>{{ activityDetail.location || '待定' }}</span>
                        </div>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <div class="detail-item">
                            <label>活动容量：</label>
                            <span>{{ activityDetail.capacity || '不限' }}</span>
                        </div>
                    </el-col>
                    <el-col :span="12">
                        <div class="detail-item">
                            <label>当前报名人数：</label>
                            <span>{{ activityDetail.currentParticipants || 0 }}</span>
                        </div>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <div class="detail-item">
                            <label>创建时间：</label>
                            <span>{{ fmtDate(activityDetail.createTime) }}</span>
                        </div>
                    </el-col>
                    <el-col :span="12">
                        <div class="detail-item">
                            <label>更新时间：</label>
                            <span>{{ fmtDate(activityDetail.updateTime) }}</span>
                        </div>
                    </el-col>
                </el-row>

                <!-- 报名状态提示 -->
                <el-row :gutter="20" v-if="applicationStatus">
                    <el-col :span="24">
                        <div class="detail-item">
                            <label>报名状态：</label>
                            <el-tag v-if="applicationStatus.status === 0" type="warning">待审核</el-tag>
                            <el-tag v-else-if="applicationStatus.status === 1" type="success">已通过</el-tag>
                            <el-tag v-else-if="applicationStatus.status === 2" type="danger">未通过</el-tag>
                            <el-tag v-else type="info">未报名</el-tag>
                            <span v-if="applicationStatus.remark" style="margin-left: 10px; color: #909399;">
                                审核意见：{{ applicationStatus.remark }}
                            </span>
                        </div>
                    </el-col>
                </el-row>
            </div>
        </div>

        <template #footer>
            <div class="dialog-footer">
                <el-button @click="detailDialogVisible = false">关闭</el-button>
                <el-button v-if="buttonConfig.show" :type="buttonConfig.type" :disabled="buttonConfig.disabled"
                    :loading="loading" @click="handleAction">
                    {{ buttonConfig.text }}
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<style scoped lang="scss">
.activity-detail {
    .detail-header {
        display: flex;
        gap: 24px;
        margin-bottom: 24px;

        .activity-image-container {
            flex-shrink: 0;

            .activity-image {
                width: 240px;
                height: 160px;
                border-radius: 12px;
                box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
                transition: transform 0.3s ease;

                &:hover {
                    transform: scale(1.02);
                }
            }

            .image-error,
            .no-image {
                width: 240px;
                height: 160px;
                border-radius: 12px;
                background: #f5f7fa;
                display: flex;
                flex-direction: column;
                align-items: center;
                justify-content: center;
                color: #909399;
                border: 2px dashed #dcdfe6;

                .el-icon {
                    font-size: 32px;
                    margin-bottom: 8px;
                }
            }
        }

        .detail-info {
            flex: 1;

            .activity-title {
                margin: 0 0 16px 0;
                color: #303133;
                font-size: 24px;
                font-weight: 600;
                line-height: 1.4;
            }

            .detail-text {
                color: #606266;
                line-height: 1.8;
                margin: 0;
                font-size: 16px;
                background: #f8f9fa;
                padding: 16px;
                border-radius: 8px;
                border-left: 4px solid #409eff;
            }
        }
    }

    .detail-content {
        .detail-item {
            margin-bottom: 20px;
            padding: 12px 0;
            border-bottom: 1px solid #f0f0f0;

            &:last-child {
                border-bottom: none;
            }

            label {
                font-weight: 600;
                color: #303133;
                margin-right: 12px;
                font-size: 15px;
                display: inline-block;
                min-width: 120px;
            }

            span {
                color: #606266;
                font-size: 15px;
            }
        }
    }
}
</style>
